DOM events

DOM (Document Object Model) events allow event-driven programming languages like JavaScript, JScript, ECMAScript, VBScript and Java to register various event handlers/listeners on the element nodes inside a DOM tree, e.g. HTML, XHTML, XUL and SVG documents.

Historically, like DOM, the event models used by various web browsers had some significant differences. This caused compatibility problems. To combat this, the event model was standardized by the W3C in DOM Level 2.

Contents

Events

HTML events

Common/W3C events

There is a huge collection of events that can be generated by most element nodes:

Note that the event classification above is not exactly the same as W3C's classification.

Category Type Attribute Description Bubbles Cancelable
Mouse click onclick Fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:
  • mousedown
  • mouseup
  • click
Yes Yes
dblclick ondblclick Fires when the pointing device button is double clicked over an element Yes Yes
mousedown onmousedown Fires when the pointing device button is pressed over an element Yes Yes
mouseup onmouseup Fires when the pointing device button is released over an element Yes Yes
mouseover onmouseover Fires when the pointing device is moved onto an element Yes Yes
mousemove onmousemove Fires when the pointing device is moved while it is over an element Yes No
mouseout onmouseout Fires when the pointing device is moved away from an element Yes Yes
Keyboard keydown onkeydown Fires before keypress, when a key on the keyboard is pressed. Yes Yes
keypress onkeypress Fires after keydown, when a key on the keyboard is pressed. Yes Yes
keyup onkeyup Fires when a key on the keyboard is released Yes Yes
HTML frame/object load onload Fires when the user agent finishes loading all content within a document, including window, frames, objects and images

For elements, it fires when the target element and all of its content has finished loading

No No
unload onunload Fires when the user agent removes all content from a window or frame

For elements, it fires when the target element or any of its content has been removed

No No
abort onabort Fires when an object/image is stopped from loading before completely loaded Yes No
error onerror Fires when an object/image/frame cannot be loaded properly Yes No
resize onresize Fires when a document view is resized Yes No
scroll onscroll Fires when a document view is scrolled Yes No
HTML form select onselect Fires when a user selects some text in a text field, including input and textarea Yes No
change onchange Fires when a control loses the input focus and its value has been modified since gaining focus Yes No
submit onsubmit Fires when a form is submitted Yes Yes
reset onreset Fires when a form is reset Yes No
focus onfocus Fires when an element receives focus either via the pointing device or by tab navigation No No
blur onblur Fires when an element loses focus either via the pointing device or by tabbing navigation No No
User interface DOMFocusIn (none) Similar to HTML focus event, but can be applied to any focusable element Yes No
DOMFocusOut (none) Similar to HTML blur event, but can be applied to any focusable element Yes No
DOMActivate (none) Similar to XUL command event. Fires when an element is activated, for instance, through a mouse click or a keypress. Yes Yes
Mutation DOMSubtreeModified (none) Fires when the subtree is modified Yes No
DOMNodeInserted (none) Fires when a node has been added as a child of another node Yes No
DOMNodeRemoved (none) Fires when a node has been removed from a DOM-tree Yes No
DOMNodeRemovedFromDocument (none) Fires when a node is being removed from a document No No
DOMNodeInsertedIntoDocument (none) Fires when a node is being inserted into a document No No
DOMAttrModified (none) Fires when an attribute has been modified Yes No
DOMCharacterDataModified (none) Fires when the character data has been modified Yes No

Note that the events whose names start with “DOM” are currently not well supported. Mozilla and Opera support DOMAttrModified, DOMNodeInserted, DOMNodeRemoved and DOMCharacterDataModified. Chrome and Safari also support these events, with the exception of DOMAttrModified.

Microsoft-specific events

Two major types of events are added by Microsoft, and in some cases can only be used in Internet Explorer. Others have been implemented as de-facto standards by other browsers.

Category Type Attribute Description Bubbles Cancelable
Clipboard cut oncut Fires after a selection is cut to the clipboard. Yes Yes
copy oncopy Fires after a selection is copied to the clipboard. Yes Yes
paste onpaste Fires after a selection is pasted from the clipboard. Yes Yes
beforecut onbeforecut Fires before a selection is cut to the clipboard. Yes Yes
beforecopy onbeforecopy Fires before a selection is copied to the clipboard. Yes Yes
beforepaste onbeforepaste Fires before a selection is pasted from the clipboard. Yes Yes
Data binding afterupdate onafterupdate Fires immediately after a databound object has been updated. Yes No
beforeupdate onbeforeupdate Fires before a data source is updated. Yes Yes
cellchange oncellchange Fires when a data source has changed. Yes No
dataavailable ondataavailable Fires when new data from a data source become available. Yes No
datasetchanged ondatasetchanged Fires when content at a data source has changed. Yes No
datasetcomplete ondatasetcomplete Fires when transfer of data from the data source has completed. Yes No
errorupdate onerrorupdate Fires if an error occurs while updating a data field. Yes No
rowenter onrowenter Fires when a new row of data from the data source is available. Yes No
rowexit onrowexit Fires when a row of data from the data source has just finished. No Yes
rowsdelete onrowsdelete Fires when a row of data from the data source is deleted. Yes No
rowinserted onrowinserted Fires when a row of data from the data source is inserted. Yes No
Mouse contextmenu oncontextmenu Fires when the context menu is shown. Yes Yes
drag ondrag Fires when during a mouse drag (on the moving Element). Yes Yes
dragstart ondragstart Fires when a mouse drag begins (on the moving Element). Yes Yes
dragenter ondragenter Fires when something is dragged onto an area (on the target Element). Yes Yes
dragover ondragover Fires when a drag is held over an area (on the target Element). Yes Yes
dragleave ondragleave Fires when something is dragged out of an area (on the target Element). Yes Yes
dragend ondragend Fires when a mouse drag ends (on the moving Element). Yes Yes
drop ondrop Fires when a mouse button is released over a valid target during a drag (on the target Element). Yes Yes
selectstart onselectstart Fires when the user starts to select text. Yes Yes
Keyboard help onhelp Fires when the user initiates help. Yes Yes
HTML frame/object beforeunload onbeforeunload Fires before a document is unloaded. No Yes
stop onstop Fires when the user stops loading the object. (unlike abort, stop event can be attached to document) No No
HTML form beforeeditfocus onbeforeeditfocus Fires before an element gains focus for editing. Yes Yes
Marquee start onstart Fires when a marquee begins a new loop. No No
finish onfinish Fires when marquee looping is complete. No Yes
bounce onbounce Fires when a scrolling marquee bounces back in the other direction. No Yes
Miscellaneous beforeprint onbeforeprint Fires before a document is printed No No
afterprint onafterprint Fires immediately after the document prints. No No
propertychange onpropertychange Fires when the property of an object is changed. No No
filterchange onfilterchange Fires when a filter changes properties or finishes a transition. No No
readystatechange onreadystatechange Fires when the readyState property of an element changes. No No
losecapture onlosecapture Fires when the releaseCapture method is invoked. No No

Note that Mozilla, Safari and Opera also support readystatechange event for the XMLHttpRequest object. Mozilla also supports the beforeunload event using traditional event registration method (DOM Level 0). Mozilla and Safari also support contextmenu, but Internet Explorer for the Mac does not.

Note that Firefox 6 and later support beforeprint and afterprint events.

Touch events

Web browsers running on modern, touch-enabled devices have events, such as "touchstart", "touchend", "touchenter", "touchleave", "touchmove", and "touchcancel". Apple's iOS and Google's Android are two examples of mobile operating systems with support for these events in their web browsers. Apple didn't join this working group, but according to an Opera employee,[1][2] has filed last minute patents, for the third time, in what seems like attempts to block forming of open standards.[3]

When you put a finger down on the screen of the touch enabled devices, it kicks off the lifecycle of touch events and the following events get triggered.

The TouchEvent, TouchPoint and TouchList interfaces are defined by w3.org in the Touch Events Specification[5]

This interface defines an individual point of contact for a touch event.

   interface TouchPoint {
   readonly attribute long         identifier;
   readonly attribute EventTarget  target;
   readonly attribute DOMTimeStamp timestamp;
   readonly attribute long         screenX;
   readonly attribute long         screenY;
   readonly attribute long         clientX;
   readonly attribute long         clientY;
   readonly attribute long         pageX;
   readonly attribute long         pageY;
   readonly attribute long         radiusX;
   readonly attribute long         radiusY;
   readonly attribute float        rotationAngle;
   readonly attribute float        force;
   readonly attribute boolean      altKey;
   readonly attribute boolean      metaKey;
   readonly attribute boolean      ctrlKey;
   readonly attribute boolean      shiftKey;
   };[6]

Attributes

  1. altKey: true if the alt (Alternate) key modifier is activated; otherwise false.
  2. clientX: x-coordinate of point relative to the viewport, excluding any scroll offset.
  3. clientY: y-coordinate of point relative to the viewport, excluding any scroll offset.
  4. ctrlKey: true if the ctrl (Control) key modifier is activated; otherwise false.
  5. force: a relative value of pressure applied, in the range 0 to 1, where 0 is no pressure, and 1 is the highest level of pressure the touch device is capable of sensing; 0 if no value is known. This attribute may not be available on all user agents or platforms. In environments where force is available, the absolute pressure represented by the force attribute, and the sensitivity in levels of pressure, may vary.
  6. identifier: An identification number for each touch point, unique to that touch point per session.
  7. metaKey: true if the meta (Meta) key modifier is activated; otherwise false. On some platforms this attribute may map to a differently-named key modifier.
  8. pageX: x-coordinate of point relative to the viewport, including any scroll offset.
  9. pageY: y-coordinate of point relative to the viewport, including any scroll offset.
  10. radiusX: The radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the x-axis, in pixels of the same scale as screenX; 1 if no value is known. This attribute may not be available on all user agents or platforms.
  11. radiusY: The radius of the ellipse which most closely circumscribes the touching area (e.g. finger, stylus) along the y-axis, in pixels of the same scale as screenY; 1 if no value is known. This attribute may not be available on all user agents or platforms.
  12. rotationAngle: The angle (in degrees) that the ellipse described by radiusX and radiusY is rotated clockwise about its center; 0 if no value is known. The value must be in the range [0, 90). If the ellipse described by radiusX and radiusY is circular, then rotationAngle must be 0.
  13. screenX: x-coordinate of point relative to the screen.
  14. screenY: y-coordinate of point relative to the screen.
  15. shiftKey: true if the shift (Shift) key modifier is activated; otherwise false.
  16. target: the original proximal event target for this touch point. The target must be an Element.
  17. timestamp: The timestamp attribute represents the time when the TouchPoint was initiated and is represented as a DOMTimeStamp.

This interface defines a list of individual points of contact for a touch event.

   interface TouchList {
   readonly attribute unsigned long length;
   caller getter TouchPoint item (in unsigned long index);
   caller getter object     identifiedPoint (in long identifier);
   };[7]

Attributes

  1. length: returns the number of touchpoints in the list.

Methods

  1. identifiedPoint : returns the first touchpoint with long identifier from the list. The value for the identifier should not be nullable and it is not an optional parameter.
  2. item : returns the touchpoint with index from the list,which is sorted in order from latest to earliest.The value for the index should not be nullable and it is an not optional parameter.

This interface defines the touchstart, touchend, touchmove, touchenter, touchleave, and touchcancel event types.

   interface TouchEvent : UIEvent {
   readonly attribute TouchList touches;
   readonly attribute TouchList targetTouches;
   readonly attribute TouchList changedTouches;
   void initTouchEvent (in DOMString type, in boolean canBubble, in boolean cancelable, in DOMWindow view, in long detail,
in boolean ctrlKey, in boolean altKey, in boolean shiftKey, in boolean metaKey, in TouchList touches, in TouchList targetTouches,
in TouchList changedTouches); };[8]

Attribute

  1. changedTouches: Its a list of TouchPoints for every point of contact which contributed to the event.
  2. targetTouches :Its a list of TouchPoints for every point of contact currently touching the surface, which started on the same target.
  3. touches:Its a list of TouchPoints for every point of contact currently touching the surface.

Methods

  1. initTouchEvent: initializes a TouchEvent created through the DocumentEvent interface.

XUL events

In addition to the common/W3C events, Mozilla defined a set of events that work only with XUL elements.

Category Type Attribute Description Bubbles Cancelable
Mouse DOMMouseScroll DOMMouseScroll Fires when the mouse wheel is moved, causing the content to scroll. Yes Yes
dragdrop ondragdrop Fires when the user releases the mouse button to drop an object being dragged. No No
dragenter ondragenter Fires when the mouse pointer first moves over an element during a drag. It is similar to the mouseover event but occurs while dragging. No No
dragexit ondragexit Fires when the mouse pointer moves away from an element during a drag. It is also called after a drop on an element. It is similar to the mouseout event but occurs during a drag. No No
draggesture ondraggesture Fires when the user starts dragging the element, usually by holding down the mouse button and moving the mouse. No No
dragover ondragover Related to the mousemove event, this event is fired while something is being dragged over an element. No No
Input CheckboxStateChange Fires when a checkbox is checked or unchecked, either by the user or a script. No No
RadioStateChange Fires when a radio button is selected, either by the user or a script. No No
close onclose Fires when a request has been made to close the window. No Yes
command oncommand Similar to W3C DOMActivate event. Fires when an element is activated, for instance, through a mouse click or a keypress. No No
input oninput Fires when a user enters text in a textbox. No No
User interface DOMMenuItemActive DOMMenuItemActive Fires when a menu or menuitem is hovered over, or highlighted. Yes No
DOMMenuItemInactive DOMMenuItemInactive Fires when a menu or menuitem is no longer being hovered over, or highlighted. Yes No
contextmenu oncontextmenu Fires when the user requests to open the context menu for the element. The action to do this varies by platform, but it will typically be a right click. No Yes
overflow onoverflow Fires a box or other layout element when there is not enough space to display it at full size. No No
overflowchanged onoverflowchanged Fires when the overflow state changes. No No
underflow onunderflow Fires to an element when there becomes enough space to display it at full size. No No
popuphidden onpopuphidden Fires to a popup after it has been hidden. No No
popuphiding onpopuphiding Fires to a popup when it is about to be hidden. No No
popupshowing onpopupshowing Fires to a popup just before it is popped open. No Yes
popupshown onpopupshown Fires to a popup after it has been opened, much like the onload event is sent to a window when it is opened. No No
Command broadcast onbroadcast Placed on an observer. The broadcast event is sent when the attributes of the broadcaster being listened to are changed. No No
commandupdate oncommandupdate Fires when a command update occurs. No No

Other events

For Mozilla and Opera 9, there are also undocumented events known as "DOMContentLoaded" and "DOMFrameContentLoaded" which fire when the DOM content is loaded. These are different from "load" as they fire before the loading of related files (e.g., images). However, DOMContentLoaded has been added to the HTML 5 Draft Specification. The "DOMContentLoaded" event was also implemented in the Webkit rendering engine build 500+.[9] This correlates to all versions of Google Chrome and Safari 3.1+. DOMContentLoaded will be implemented in Internet Explorer 9.[10]

Opera 9 also supports the Web Forms 2.0 events "DOMControlValueChanged", "invalid", "forminput" and "formchange".

Event flow

Consider the situation when there are 2 elements nested together. Both have event handlers registered on the same event type, say "click". When the user clicks on the inner element, there are two possible ways to handle it:

W3C takes a middle position in this struggle. Events are first captured until it reaches the target element, and then bubbled up. During the event flow, an event can be responded to at any element in the path (an observer) in either phase by causing an action, and/or by stopping the event (with method event.stopPropagation() for W3C-conforming browsers and command event.cancelBubble = true for Internet Explorer), and/or by cancelling the default action for the event.

Event object

The Event object provides a lot of information about a particular event, including information about target element, key pressed, mouse button pressed, mouse position, etc. Unfortunately, there are very serious browser incompatibilities in this area. Hence only the W3C Event object is discussed in this article.

Event properties
Type Name Description
DOMString type The name of the event (case-insensitive).
EventTarget target Used to indicate the EventTarget to which the event was originally dispatched.
EventTarget currentTarget Used to indicate the EventTarget whose EventListeners are currently being processed.
unsigned short eventPhase Used to indicate which phase of event flow is currently being evaluated.
boolean bubbles Used to indicate whether or not an event is a bubbling event.
boolean cancelable Used to indicate whether or not an event can have its default action prevented.
DOMTimeStamp timeStamp Used to specify the time (in milliseconds relative to the epoch) at which the event was created.
Event methods
Name Argument type Argument name Description
stopPropagation To prevent further propagation of an event during event flow.
preventDefault To cancel the event if it is cancelable, meaning that any default action normally taken by the implementation as a result of the event will not occur.
initEvent DOMString eventTypeArg Specifies the event type.
boolean canBubbleArg Specifies whether or not the event can bubble.
boolean cancelableArg Specifies whether or not the event's default action can be prevented.

Event handling models

DOM Level 0

This event handling model was introduced by Netscape Navigator, and remains the most cross-browser model as of 2005. There are two model types: inline model and traditional model.

Inline model

In the inline model, event handlers are added as attribute of element. Event handlers can also be removed:

<head>
  <script type="text/javascript">
    function helloWorld( name )
    {
        window.alert( "Hello " + name );
    }
 
    function removeHandler(object)
    {
        object.onclick = null;
    }
  </script>
</head>
<body>
 
 
Hello <a href="http://www.example.com" onclick="helloWorld('Joe'); removeHandler(this);">Joe</a>!
 
</body>

In the example above, an alert dialog box with the message "Hello Joe" will appear when the hyperlink is clicked and open URI in href attribute.

The default action can be cancelled by returning false in the event handler:

<head>
  <script type="text/javascript">
    function helloWorld( name )
    {
        window.alert( "Hello " + name );
    }
  </script>
</head>
<body>
 
 
Stay <a href="http://www.example.com" onclick="helloWorld('Joe'); return false;">here</a>!
 
</body>

In the example above, the browser will not go to "example.com" when the hyperlink is clicked.

One common misconception with the inline model is the belief that it allows the registration of event handlers with custom arguments, e.g. name in the helloWorld function. While it may seem like that is the case in the example above, what is really happening is that the JavaScript engine of the browser creates an anonymous function containing the statements in the onclick attribute. The onclick handler of the element would be bound to the following anonymous function:

function()
{
    helloWorld('Joe');
    return false;
}

This limitation of the JavaScript event model is usually overcome by assigning attributes to the function object of the event handler or by using closures.

Traditional model

In the traditional model, event handlers can be added/removed by scripts. Like the inline model, each event can only have one event handler registered. The event is added by assigning the handler name to the event property of the element object. To remove an event handler, simply set the property to null:

<head>
  <script type="text/javascript">
    function helloWorld()
    {
        window.alert( "Hello World" );
    }
 
    // Add an event handler
    window.onload = helloWorld;
 
    // Add another event handler
    document.onclick = helloWorld;
 
    // Remove the event handler just added
    document.onclick = null;
  </script>
</head>
<body>
 
 
Hello World!
 
</body>

To add parameters:

var name='Joe';
document.onclick = (function(name)
{
 return function () {
   alert('Hello '+ name +'!');
 }
})(name);

Inner functions preserve their scope.

DOM Level 2

The W3C designed a more flexible event handling model in DOM Level 2.

Name Description Argument type Argument name
addEventListener Allows the registration of event listeners on the event target. DOMString type
EventListener listener
boolean useCapture
removeEventListener Allows the removal of event listeners from the event target. DOMString type
EventListener listener
boolean useCapture
dispatchEvent Allows to send the event to the subscribed event listeners. Event evt

Some useful things to know :

The main difference from the traditional model is that multiple event handlers can be registered for the same event. The useCapture option can also be used to specify that the handler should be called in the capture phase instead of the bubbling phase. This model is supported by Mozilla, Opera, Safari, Chrome and Konqueror.

A rewrite of the example used in traditional model:

<head>
  <script type="text/javascript">
    function helloWorld()
    {
        window.alert( "Hello World" );
    }
 
    // Add an event handler
    window.addEventListener( "load", helloWorld, false );  // bubbling phase
 
    // Add another event handler
    document.addEventListener( "click", helloWorld, true );  // capture phase
 
    // Remove the event handler just added
    document.removeEventListener( "click", helloWorld, true );
  </script>
</head>
<body>
 
 
Hello World!
 
</body>

Microsoft-specific model

Microsoft does not follow the W3C model up until Internet Explorer 8, as its own model was created prior to the ratification of the W3C standard. Internet Explorer 9 is supposed to follow DOM level 3 events.[11]

Name Description Argument type Argument name
attachEvent Similar to W3C's addEventListener method. String sEvent
Pointer fpNotify
detachEvent Similar to W3C's removeEventListener method. String sEvent
Pointer fpNotify
fireEvent Similar to W3C's dispatchEvent method. String sEvent
Event oEventObject

Some useful things to know :

Again, this model differs from the traditional model in that multiple event handlers can be registered for the same event. However the useCapture option can not be used to specify that the handler should be called in the capture phase. This model is supported by Microsoft Internet Explorer and Trident based browsers (e.g. Maxthon, Avant Browser).

A rewrite of the example used in traditional model:

<head>
  <script type="text/javascript">
    function helloWorld()
    {
        window.alert( "Hello World" );
    }
 
    // Add an event handler
    window.attachEvent( "onload", helloWorld );
 
    // Add another event handler
    document.attachEvent( "onclick", helloWorld );
 
    // Remove the event handler just added
    document.detachEvent( "onclick", helloWorld );
  </script>
</head>
<body>
 
 
Hello World!
 
</body>

See also

References

External links

References